import { useState, useEffect, useRef } from 'react';

export const useWebSocket = (url, onMessage) => {
  const [socket, setSocket] = useState(null);
  const [connectionStatus, setConnectionStatus] = useState('disconnected');
  const retryCountRef = useRef(0);
  const reconnectTimeoutRef = useRef(null);
  const heartbeatIntervalRef = useRef(null);
  const MAX_RETRIES = 5;
  const HEARTBEAT_INTERVAL = 30000; // 30秒心跳间隔

  const connectWebSocket = () => {
    // 如果已有连接，先关闭
    if (socket && socket.readyState === WebSocket.OPEN) {
      socket.close();
    }
    
    setConnectionStatus('connecting');
    console.log(`正在尝试连接WebSocket (第${retryCountRef.current + 1}次重试)...`);
    const ws = new WebSocket(url);
    
    ws.onopen = () => {
      console.log('WebSocket连接已建立', url);
      setConnectionStatus('connected');
      retryCountRef.current = 0;
      
      // 启动心跳检测
      heartbeatIntervalRef.current = setInterval(() => {
        if (ws.readyState === WebSocket.OPEN) {
          ws.send(JSON.stringify({ type: 'heartbeat' }));
          console.log('发送心跳包');
        }
      }, HEARTBEAT_INTERVAL);
    };
    
    ws.onmessage = (event) => {
      try {
        const message = JSON.parse(event.data);
        console.log('收到WebSocket消息:', message);
        
        // 过滤掉msg_type为51的消息
        if (message.msg_type == 1||message.msg_type == 3||message.msg_type == 49) {
          // 文本消息直接传递
          onMessage(message);
        } 
      } catch (error) {
        console.error('消息解析错误:', error);
      }
    };
    
    ws.onerror = (error) => {
      console.error('WebSocket错误:', {
        url,
        error: error.message || error,
        retryCount: retryCountRef.current,
        nextRetryIn: Math.min(1000 * Math.pow(2, retryCountRef.current), 30000)
      });
      setConnectionStatus('error');
      handleReconnect();
    };
    
    ws.onclose = (event) => {
      console.log('WebSocket连接已关闭', {
        url,
        code: event.code,
        reason: event.reason,
        wasClean: event.wasClean
      });
      setConnectionStatus('disconnected');
      if (!event.wasClean) {
        handleReconnect();
      }
    };
    
    setSocket(ws);
  };

  const handleReconnect = () => {
    if (retryCountRef.current < MAX_RETRIES) {
      const delay = Math.min(1000 * Math.pow(2, retryCountRef.current), 30000);
      console.log(`将在${delay}ms后尝试重新连接...`);
      reconnectTimeoutRef.current = setTimeout(() => {
        retryCountRef.current += 1;
        connectWebSocket();
      }, delay);
    } else {
      console.error(`已达到最大重试次数(${MAX_RETRIES}次)，停止重连`);
    }
  };



  useEffect(() => {
    // 仅在url变化时重新连接
    connectWebSocket();
    
    return () => {
      if (reconnectTimeoutRef.current) {
        clearTimeout(reconnectTimeoutRef.current);
      }
      if (heartbeatIntervalRef.current) {
        clearInterval(heartbeatIntervalRef.current);
      }
      if (socket && socket.readyState === WebSocket.OPEN) {
        socket.close();
      }
    };
  }, [url]);

  return { socket, connectionStatus };
};

export default useWebSocket;